package com.yehun.utils;

import java.io.*;
import java.util.Properties;

/**
 * properties文件
 * Created by Genius on 2017/4/10 0010.
 */
public class PropertyUtils {

    public static String getMessage(String key) {
        return getString(MESSAGE_PATH, key);
    }

    public static String getConfig(String key) {
        return getString(CONFIG_PATH, key);
    }

    public static <T> T getConfig(String key, Class<T> t) {
        switch (t.getName()) {
            case "java.lang.Integer":
                return (T) ParseUtils.parseInt(getConfig(key));
            case "java.lang.Boolean":
                return (T) ParseUtils.parseBoolean(getConfig(key));
        }
        return null;
    }

    public static String getDatasource(String key) {
        return getString(DATASOURCE_PATH, key);
    }


    private static final String CONFIG_PATH = "properties/config.properties";
    private static final String MESSAGE_PATH = "properties/message.properties";
    private static final String DATASOURCE_PATH = "properties/datasource.properties";


    private static Object getObject(String path, String key) {
        Properties properties = new Properties();
        String absolutePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        try {
            properties.load(new FileInputStream(absolutePath + path));
        } catch (IOException e) {
            //e.printStackTrace();
        }
        if(properties != null) {
            if(properties.containsKey(key)) {
                return properties.get(key).toString();
            }
        }
        return null;
    }

    private static String getString(String path, String key) {
        Object object = getObject(path, key);
        if(object != null) return object.toString();
        return "";
    }

    private static int getInt(String path, String key) {
        Object object = getObject(path,key);
        if(object == null) return 0;
        return Integer.valueOf(object.toString());
    }

    private static boolean getBoolean(String path, String key) {
        Object object = getObject(path,key);
        if(object == null) return false;
        return Boolean.valueOf(object.toString());
    }
}